class dryCascadeSelect extends HTMLElement{
    constructor(){
        super();
        var that = this;
        var ref = get("ref");
        var callback = get("callback");
        var label = get("label");
        var unique = get("unique");
        var text = get("text");
        var value = get("value");
        var url = get("url");
        var convertConfig = get("convert-config");
        var card = get("card");
        var cardColor = get("cardColor", "#009688");
        var verify = get("verify", "[]");
        var list = [];
        var nameList = [];
        var textList = [];
        var verifyList = [];
        var valueList = [];
        var length = 0;
        
        function get(name, theDefault = "")
        {
            if(that.hasAttribute(name)){
                return that.getAttribute(name);
            }
            return theDefault;
        }
        
        function $$(id)
        {
            return document.getElementById(id);
        }
        
        function getUnique()
        {
            var d = new Date();
            var temp = Math.random() + "";
            return "g_" + d.getTime() + "_" + temp.substr(2);
        }
        
        function getRequest(url, successCallback, failCallback)
        {
            function success(response)
            {
                if(response.ok == true && response.status == 200){
                    response.json().then(function(json){
                        successCallback(json);
                    });
                }
            }
            
            function fail(response)
            {
                if(typeof(failCallback) == "function"){
                    failCallback(response);
                }
                else{
                    console.log(response);
                }
            }
            
            fetch(url).then(success).catch(fail);
        }
        
        function runCallback(p)
        {
            var f = window[callback];
            if(!f){
                setTimeout(function(){
                    runCallback(p);
                }, 500);
            }
            else{
                f(p);
                that.setAttribute("ok", "1");
            }
        }
        
        function convert(list)
        {
            var result = [];
            var config = JSON.parse(convertConfig);
            for(var i in list){
                var item = list[i];
                var temp = {
                    "id": item[config.id],
                    "parent": item[config.parent],
                    "grade": item[config.grade],
                    "name": item[config.name]
                };
                result.push(temp);
            }
            return result;
        }
        
        function searchData(grade, parent)
        {
            var returnList = [];
            for(var i in list){
                var item = list[i];
                if(item.grade == grade){
                    if(parent){
                        if(item.parent == parent){
                            returnList.push(item);
                        }
                    }
                    else{
                        returnList.push(item);
                    }
                }
            }
            return returnList;
        }
        
        function getVerify(i, name)
        {
            if(verifyList.length > i && verifyList[i] != ""){
                return verifyList[i];
            }
            return name;
        }
        
        function finish(json)
        {
            list = convert(json.data);
            nameList = JSON.parse(unique);
            textList = JSON.parse(text);
            verifyList = JSON.parse(verify);
            length = nameList.length;
            var html = [];
            html.push(`<div class="layui-form-item">`);
            /**/
            if(card == 0){
                html.push(`<label class="layui-form-label">${label}</label>`);
                for(var i = 0;i < length;i++){
                    var name = nameList[i];
                    var grade = i + 1;
                    var v = getVerify(i, name);
                    html.push(`<div class="layui-input-inline"><select id="${name}" grade="${grade}" name="${name}" lay-verify="${v}" lay-filter="${name}"></select></div>`);
                }
            }
            else{
                html.push(`<div class="layui-card">`);
                html.push(`<div class="layui-card-header" style="background-color:${cardColor};border:1px solid ${cardColor};color:white;">${label}</div>`);
                html.push(`<div class="layui-card-body" style="border:1px solid ${cardColor};margin-top:-1px;">`);
                for(var i = 0;i < length;i++){
                    var name = nameList[i];
                    var grade = i + 1;
                    var marginTop = 10;
                    if(i == 0){
                        marginTop = 0;
                    }
                    var v = getVerify(i, name);
                    html.push(`<div class="layui-input-block" style="margin-left:0;margin-top:${marginTop}px;"><select id="${name}" grade="${grade}" name="${name}" lay-verify="${v}" lay-filter="${name}"></select></div>`);
                }
                html.push(`</div>`);
                html.push(`</div>`);
            }
            /**/
            html.push(`</div>`);
            if(ref == ""){
                ref = getUnique();
                that.insertAdjacentHTML("afterend", `<div id="${ref}"></div>`);
            }
            $$(ref).innerHTML = html.join("");
            runCallback(commonCallback);
        }
        
        function commonCallback(y)
        {
            function makeSelect(id, listData, defaultValue, firstData)
            {
                var selector = "#" + id;
                if(!$(selector).length){
                    return false;
                }
                listData.unshift(firstData);
                var html = [];
                for(var i in listData){
                    var item = listData[i];
                    var selected = "";
                    if(item.id == defaultValue){
                        selected = "selected='true'";
                    }
                    html.push(`<option value="${item.id}" ${selected}>${item.name}</option>`);
                }
                $(selector).html(html.join(''));
            }
            
            function addEventListener()
            {
                for(var i = 0;i < length;i++){
                    var name = nameList[i];
                    form.on(`select(${name})`, function(currentData){
                        doSelectChange(currentData);
                    });
                }
            }
            
            function doSelectChange(currentData)
            {
                var thisGrade = $(currentData.elem).attr("grade");
                var nextGrade = parseInt(thisGrade) + 1;
                var nextNextGrade = nextGrade + 1;
                var thisValue = parseInt(currentData.value);
                var listData = searchData(nextGrade, thisValue);
                makeSelect(nameList[thisGrade], listData, 0, makeFirstData(thisGrade));
                for(var i = nextNextGrade; i <= length; i++){
                    var temp = "#" + nameList[i - 1];
                    if($(temp).length){
                        $(temp).find("option").not(":first").remove();
                    }
                }
                for(var i = nextGrade; i <= length; i++){
                    var temp = "#" + nameList[i - 1];
                    if($(temp).length){
                        $(temp).trigger("change");
                    }
                }
                render();
            }
            
            function makeFirstData(index)
            {
                return {"id": "0", "name": textList[index]};
            }
            
            function render()
            {
                form.render("select");
            }
            
            function initData()
            {
                function initDataForNew()
                {
                    var listData = searchData(1, 0);
                    makeSelect(nameList[0], listData, 0, makeFirstData(0));
                }
                
                function initDataForEdit()
                {
                    for(var i = 1;i <= valueList.length;i++){
                        var listData = [];
                        if(i == 1){
                            listData = searchData(i, 0);
                        }
                        else{
                            listData = searchData(i, valueList[i - 2]);
                        }
                        makeSelect(nameList[i - 1], listData, valueList[i - 1], makeFirstData(i - 1));
                    }
                }
                
                if(value == ""){
                    initDataForNew();
                }
                else{
                    valueList = JSON.parse(value);
                    if(valueList.length == 0){
                        initDataForNew();
                    }
                    else{
                        initDataForEdit();
                    }
                }
            }
            
            var form = y.form;
            var $ = y.jquery;
           initData();
           addEventListener();
           render();
        }
        
        if(callback == ""){
            callback = "dryCallback";
        }
        getRequest(url, finish);
    }
};
window.customElements.define('dry-cascade-select', dryCascadeSelect);